package com.example.springboot.controller;


import com.example.springboot.aspect.HttpAspect;
import com.example.springboot.domain.Girl;
import com.example.springboot.domain.Result;
import com.example.springboot.properties.GirlProperties;
import com.example.springboot.repository.GirlRepository;
import com.example.springboot.service.GirlService;
import com.example.springboot.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/***
 * 增加的url不一样。 查询、更新、删除的rest url都一样
 */
@RestController
@RequestMapping("/girls")
public class GirlController {

    @Autowired
    private GirlProperties girlProperties;
    @Autowired
    private GirlRepository girlRepository;
    @Autowired
    private GirlService girlService;

    @RequestMapping("/testConfigurattion")
    //批量读取配置文件中的属性值（以组为单位）
    public String testConfigurattion(){
        return girlProperties.getId() + girlProperties.getAge() + girlProperties.getCupSize();
    }

    @PostMapping()
    public Result girlAdd(@Valid Girl girl, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
        }
        Girl girlSave = new Girl();
        girlSave.setId(girl.getId());
        girlSave.setCupSize(girl.getCupSize());
        girlSave.setAge(girl.getAge());
        return ResultUtil.success(girlRepository.save(girlSave));
    }

    @GetMapping("/{id}")
    public Girl queryOne(@PathVariable("id")Integer id){
        return girlRepository.findOne(id);
    }

    @PutMapping("/{id}")
    public Girl updateOne(Girl girl){
        Girl girlSave = new Girl();
        girlSave.setId(girl.getId());
        girlSave.setCupSize(girl.getCupSize());
        girlSave.setAge(girl.getAge());
        return girlRepository.save(girl);
    }

    @DeleteMapping("/{id}")
    public void girlDelete(@PathVariable("id")Integer id){
        girlRepository.delete(id);
    }

    //根据年龄查，自己定义方法
    @GetMapping("/age/{age}")
    public List<Girl> findByAge(@PathVariable("age")Integer age){
        return girlRepository.findByAge(age);
    }

    //事务的使用，加入多个女生
    @PostMapping("/someGirls")
    public void girlsAdd(){
        girlService.insertTwo();
    }

    @GetMapping("/getAge/{id}")
    public void getAge(@PathVariable("id")Integer id) throws  Exception{
        girlService.getAge(id);
    }

}